//
//  HistoryCarViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//
import UIKit


final class AutoCheckViewController: UIViewController, Alertable {
    
    // MARK: - Outlets
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(AutoCheckCell.self, forCellReuseIdentifier: "AutoCheckCell")
        tableView.register(AutoCheckInfoCell.self, forCellReuseIdentifier: "AutoCheckInfoCell")
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    private lazy var hintLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 14)
        lbl.textColor = .rgb(60,72,88)
        
        var normText = NSMutableAttributedString(string: "Вы можете купить историю перерегистрации по вашему автомобилю за ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)])
        var boldText = NSMutableAttributedString(string: "1 000₸", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: .bold)])
        normText.append(boldText)
        lbl.attributedText = normText
        lbl.numberOfLines = 0
        return lbl
    }()
    
    private lazy var submitBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .blueColor
        btn.layer.cornerRadius = 15
        btn.setTitleColor(.white, for: .normal)
        btn.setTitle("Купить отчет за 1 000₸", for: .normal)
        return btn
    }()
    
    private lazy var spinnerView = SpinnerView()
    
    // MARK: - Props
    
    public var vin: String!
    
    private lazy var viewModel:AutoCheckViewModel = {
        let vm = AutoCheckViewModel()
        vm.delegate = self
        return vm
    }()
    
    private let borderColor = UIColor.rgb(227,229,299)

    
    // MARK: - Actions
    
    @objc private func goBack (sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func doSharing (sender: UIBarButtonItem) {
        
    }
    
    // MARK: - Init
    
    override func viewWillAppear(_ animated: Bool) {
        setUpNav()
        navigationController?.view.backgroundColor = UIColor.white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addViews()
        viewModel.loadCheckAuto(vin: self.vin)
    }
}


extension AutoCheckViewController: ViewModelProtocol {
    func updateCities(cities: [City]?) {}
    
    func updateSpinner(showSpinner: Bool) {
        showSpinner ? spinnerView.startAnimating() : spinnerView.stopAnimating()
        view.isUserInteractionEnabled = !showSpinner
    }
    
    func didHappenError(error: RequestError) {
        self.alertError(error: error)
    }
    
    func updatePosts() {
        self.tableView.reloadData()
    }
}


// MARK: - UI Table View

extension AutoCheckViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.data[section].items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let item = viewModel.data[indexPath.section].items[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: type(of: item).reuseId)!
        item.configure(cell: cell, index: indexPath.row)
        self.handleCell(cell: cell, indexPath: indexPath)
        return cell
    }

    
    private func handleCell (cell: UITableViewCell, indexPath: IndexPath) {
        if indexPath.row == viewModel.data[indexPath.section].items.count - 1 {
            if cell is AutoCheckCell {
                (cell as! AutoCheckCell).setUpLastRow()
            }
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 36))
        headerView.backgroundColor = .white
        let headerTitle = UILabel()
        headerTitle.font = .systemFont(ofSize: 16)
        headerTitle.textColor = .greyColor
        
        if !(viewModel.data[section].items is [AutoCheckCellConfigurator]) {
            headerTitle.textColor = .orange
        }
        
        headerTitle.text = viewModel.data[section].name
        headerView.addSubview(headerTitle)
        headerTitle.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(16)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(-12)
        }
        return headerView
    }
    
    private func createHeaderView () -> UIView? {
        
        let topHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 64))
        topHeaderView.backgroundColor = .white
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 24)
        lbl.textColor = .darkBlueColor
        lbl.textAlignment = .left
        lbl.text = "Отчет"
        
        topHeaderView.addSubview(lbl)
        lbl.snp.makeConstraints { (make) in
            make.trailing.top.equalToSuperview().inset(16)
            make.leading.equalToSuperview()
            make.bottom.equalToSuperview().offset(-4)
            make.height.equalTo(30)
        }
        
        return topHeaderView
    }
}



// MARK: - UI


extension AutoCheckViewController {
    
    private func addViews() {
        view.backgroundColor = .white
        tableView.backgroundColor = .white
        tableView.tableHeaderView = self.createHeaderView()
        view.addSubview(tableView)
        view.addSubview(submitBtn)
        view.addSubview(hintLbl)
        view.addSubview(spinnerView)
        
        submitBtn.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-20)
            make.height.equalTo(44)
        }
        
        hintLbl.snp.makeConstraints { (make) in
            make.bottom.equalTo(submitBtn.snp.top).offset(-17)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(hintLbl.snp.top).offset(-20)
            make.top.equalToSuperview()
        }
        
        spinnerView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    private func setUpNav () {
        self.navigationItem.title = "История авто"
        self.addBackBtn()
        self.addShareBtn()
    }
    
    private func addBackBtn () {
        let backButton = UIBarButtonItem(image: UIImage(named: "cancel"), style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        
        self.navigationItem.hidesBackButton = true
        self.navigationItem.leftBarButtonItem = backButton
    }
    
    private func addShareBtn () {
        let shareButton = UIBarButtonItem(image: UIImage(named: "share"), style: .plain, target: self, action: #selector(doSharing(sender:)))
        shareButton.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = shareButton
    }
}
